package hu.uszeged.inf.stud.prf.todo.controller.user;

import hu.uszeged.inf.stud.prf.todo.dao.user.UserDAO;
import hu.uszeged.inf.stud.prf.todo.entity.user.User;

import java.io.Serializable;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;

@Named
public class Registration implements Serializable {

	private static final long serialVersionUID = -6501275750966617332L;

	@Inject
	Credentials credentials;

	@Inject
	UserDAO userdao;

	@Inject
	Login login;

	public String registerAction() {
		if(!credentials.getPassword().equals(credentials.getPassword2())){ //nem egyeznek meg a jelszavak
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("The given passwords must match!"));
			return "/content/registration?faces-redirect=false";
		}
		if(userdao.getUserByName(credentials.getUsername())!=null){ //már van ilyen user
			  FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Username: \""+credentials.getUsername()+"\" already exists!"));
			return "/content/registration?faces-redirect=false";
		}
		User u = new User();
		u.setName(credentials.getUsername());
		u.setPassword(credentials.getPassword());
		userdao.makePersistent(u);
		userdao.flush();
		login.setUser(userdao.findByExample(u, null).get(0));
		return "/index?faces-redirect=true";
		
	}

	

}
